package javango.forms.widgets;

import java.util.Map;

import javango.forms.fields.ChoiceField;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SelectWidget extends BaseChoicesWidget {

	private final static Log log = LogFactory.getLog(SelectWidget.class);

	public SelectWidget() {
		super(null);
	}

	public SelectWidget(Map<String, Object> attrs) {
		super(attrs);
	}

	public SelectWidget(Map<String, Object> attrs, ChoiceField field) {
		super(attrs);
		setField(field);
	}
	
	public SelectWidget(Map<String, Object> attrs, Map<String, Object> choices) {
		super(attrs);
		setChoices(choices);
	}
	
	@Override
	public String asText(Object value) {
		Object choiceValue = this.getField().getByKey(value == null ? null : value.toString());		
		return choiceValue == null ? "" : choiceValue.toString();
	}

	public String render(String name, Object value, Map<String, Object> attrs) {
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("name", name);

		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String) finalAttrs.get("id"),
					name));
		}
		if (finalAttrs.containsKey("READONLY")) {
			finalAttrs.remove("READONLY");
			finalAttrs.put("disabled", "disabled");
		}

		StringBuilder b = new StringBuilder("<select");
		Util.flatatt(finalAttrs, b);
		b.append(">");
		
		String strValue = value == null ? "" : value instanceof String[] ? ((String[])value)[0] : value.toString();

		String optionHtml = "<option value=\"%s\" %s>%s</option>"; // value, selected, display

		// TODO while setting allownull=true this works great for putting -- and still forcing the user to select it may not be intuitave
		// heck this should alwasy be prepended to the list if nothing is marked as selected!!
		if (getField() != null && (getField().isAllowNull() || !getField().isRequired())) { // add a blank option as the first value
			b.append(String.format(optionHtml, "", "", "--"));
		}

		for (Map.Entry<String, Object> entry : getMyChoices().entrySet()) {
				String optionValue = entry.getKey();
				String selected = value == null ? "" : strValue.equals(optionValue) ? "selected=\"selected\"" : "";
				log.debug("optionValue : '" + optionValue + "'; value : '"
						+ value + "'");
				b.append(String.format(optionHtml, optionValue.toString(),
						selected, entry.getValue().toString()));
			}
		b.append("</select>");
		return b.toString();
	}

}
